/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.dona.imsidetector.fragment;

import static android.view.View.X;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.dona.imsidetector.R;
import com.dona.imsidetector.adpter.SimpleRecyclerAdapter;
import com.dona.imsidetector.core.BaseFragment;
import com.dona.imsidetector.databinding.FragmentDetectorBinding;
import com.dona.imsidetector.db.dao.ItemDao;
import com.dona.imsidetector.db.dao.ListDao;
import com.dona.imsidetector.db.entity.BwList;
import com.dona.imsidetector.db.entity.Imsi;
import com.dona.imsidetector.db.entity.ListItem;
import com.dona.imsidetector.fragment.linkage.custom.CustomGroupedItem;
import com.dona.imsidetector.socket.UDPClient;
import com.dona.imsidetector.socket.UDPSocket;
import com.dona.imsidetector.utils.IMSIUtil;
import com.dona.imsidetector.utils.MMKVUtils;
import com.dona.imsidetector.utils.XToastUtils;
import com.google.gson.Gson;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xui.widget.popupwindow.popup.XUIListPopup;
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup;
import com.xuexiang.xui.widget.spinner.materialspinner.MaterialSpinner;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;


import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.io.IOException;
import java.text.BreakIterator;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static androidx.constraintlayout.widget.Constraints.TAG;
import static com.dona.imsidetector.socket.UDPSocket.imsilist;
import static com.dona.imsidetector.socket.UDPSocket.imsistrlist;
import static com.xuexiang.xui.utils.WidgetUtils.initRecyclerView;

import static java.lang.Double.isNaN;

import org.xutils.x;

/**
 * 这个只是一个空壳Fragment，只是用于演示而已
 *
 * @author xuexiang
 * @since 2019-07-08 00:52
 */
@Page(name = "侦码定位")
public class DetectorFragment extends BaseFragment<FragmentDetectorBinding> implements View.OnClickListener, AMapLocationListener {
    public static final int MSG_NEW_IMSI = 0x11;
    public static double lat;
    public static double lng;
    private UDPSocket socket;
    private static UDPClient[] udpClients;
//    SwipeRefreshLayout refreshLayout;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    private SimpleRecyclerAdapter mAdapter;
    WifiManager wifiManager = null;
//    SwipeRecyclerView recyclerView;
//
//    Button scanBtn;
//
//    Button syncTimeBtn;
//    Button netModeBtn;
//    Button workTypeBtn;
//
//    LinearLayout scanicon_layout;
//
//    TextView scanmsg_90;
//
//    TextView scanicon;
//
//    private ClearEditText msg;

    private int count;

    private Timer timer;
    private TimerTask timerTask;
    private XUIListPopup mListPopup;

    String[] workTypelistItems = new String[]{
            "0-标准围栏",
            "1-黑名单管控(无消息)",
            "4-黑名单管控(发消息)",
            "5-非白名单",
            "6-非白名单，黑名单管控(发消息)",
    };

    String[] netModelistItems = new String[]{
            "GSM_WB",   //GSM96X模式，支持96载频内的两个单载频小区。
            "GSM",      //GSM9X模式，支持一个双载频小区，两个载频在9X范围内。
            "WCDMA",     //WCDMA单载频小区
            "FDD-LTE",  //FDD LTE小区
            "TDD-LTE",   //TDD LTE小区
    };


    //黑白名单
    List<BwList> bwLists = null;

    private String whiteList;
    private String blackList;
    private Integer select_isp = 1;
    private String choose_ip = null;
    private HashMap<String, String> workTypeMap;


    @NonNull
    @Override
    protected FragmentDetectorBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentDetectorBinding.inflate(inflater, container, false);
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {

        initData();
        whiteList = "";
        blackList = "";
        wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        msg = this.findViewById(R.id.msg);
//        socket = new UDPSocket(this.getContext());
//        socket.startUDPSocket();
        binding.scanBtn.setOnClickListener(this);
        binding.syncTimeBtn.setOnClickListener(this);
        binding.netModeBtn.setOnClickListener(this);
        binding.workTypeBtn.setOnClickListener(this);
        binding.xxooBtn.setOnClickListener(this);
        binding.rebootBtn.setOnClickListener(this);
        binding.uploadDataBtn.setOnClickListener(this);


        initRecyclerView(binding.recyclerView);

        //必须在setAdapter之前调用
        binding.recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        //必须在setAdapter之前调用
        binding.recyclerView.setOnItemMenuClickListener(mMenuItemClickListener);
        binding.recyclerView.setAdapter(mAdapter = new SimpleRecyclerAdapter());

        binding.server.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(MaterialSpinner materialSpinner, int i, long l, Object o) {
                Log.e(TAG, "onItemSelected: " + materialSpinner.getText());
                choose_ip = materialSpinner.getText().toString().contains("全部") ? null : "192.168.1." + materialSpinner.getText().toString();
            }
        });
//        count = socket.getSize();

        /**
         * 黑名单初始化。。。
         */
        getBWlist();
//        startTimerTask();


        binding.scaniconLayout.setVisibility(View.VISIBLE);

        /**
         * 初始化配置
         * ip  对应的频点   90 -FDD  91 TDD
         *
         *
         */

        Log.e(TAG, "initViews: " +MMKVUtils.getString("setting",null) );
        if(null != MMKVUtils.getString("setting",null)){
            Log.e(TAG, "initViews3: " +MMKVUtils.getString("setting",null) );

            settingMap = new Gson().fromJson(MMKVUtils.getString("setting",null),HashMap.class);
        }else {
            settingMap = new HashMap<>();
            settingMap.put( "192.168.1.90","FDD-LTE");
            settingMap.put( "192.168.1.91","TDD-LTE");
            settingMap.put( "192.168.1.92","TDD-LTE");
            settingMap.put( "192.168.1.93","TDD-LTE");
            settingMap.put( "192.168.1.94","TDD-LTE");
            MMKVUtils.put("setting",new Gson().toJson(settingMap));
            Log.e(TAG, "initViews2: " +MMKVUtils.getString("setting",null) );

        }
//        settingMap.put("192.168.1.92","WCDMA");




        getFreqItems();

//        mlocationClient = new AMapLocationClient(getContext());
////初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
////设置定位监听
//        mlocationClient.setLocationListener(this);
////设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
////设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
////设置定位参数
//        mlocationClient.setLocationOption(mLocationOption);
//// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//// 在定位结束后，在合适的生命周期调用onDestroy()方法
//// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
////启动定位
//        mlocationClient.startLocation();


        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if(UDPClient.imsilist!=null && UDPClient.imsilist.size()>0) {
                    List<Imsi> imsis = new ArrayList<>();
                    for (Imsi imsi : UDPClient.imsilist) {
                        if (imsi.getIsRead() == 0) {
                            imsis.add(imsi);
                        }
                    }

                    if(imsis.size()>0) {
                        uploadData(imsis);
                        imsis = null;
                    }
                }
            }
        };

        timer.schedule(timerTask,3000,5000);

    }

    String missionId = null;
    List<ListItem> blistItems = null;
    List<ListItem> wlistItems = null;
    /**
     * 获取黑白名单
     */
    private void getBWlist() {


        //黑白名单
        missionId  = MMKVUtils.getString("missionId","");
        if(StringUtils.isEmpty(missionId)){
            XToastUtils.error("未选择任务！！！");
            openNewPage(BlackWhiteFragment.class);
            return;
        }
//        bwLists = (List<BwList>) ListDao.find(missionId);


        blistItems = ItemDao.findBOrWListByListId(missionId, 0);
        wlistItems = ItemDao.findBOrWListByListId(missionId, 1);
        if (null != blistItems && blistItems.size() > 0) {
            for (ListItem item : blistItems) {
                if (item.getImsiAddr() != null && !"null".equals(item.getImsiAddr()) && !"".equals(item.getImsiAddr())) {
                    blackList += item.getImsiAddr();
                }
            }
        }
        if (null != wlistItems && wlistItems.size() > 0) {
            for (ListItem item : wlistItems) {
                if (item.getImsiAddr() != null && !"null".equals(item.getImsiAddr()) && !"".equals(item.getImsiAddr())) {
                    whiteList += item.getImsiAddr();
                }
            }
        }
    }

    private OkHttpClient okHttpClient = new OkHttpClient();
    public static final String hostAddress = "http://nasas.oicp.vip:889/hnwy-uas/";

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    List<Map<String, Object>> bodyDataCache;

    private void uploadData(List<Imsi> imsis) {
        bodyDataCache = new ArrayList<>();
        // 上传数据开始
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String date = df.format(curDate);
        SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
        String time = tf.format(curDate);

        // gImsi/list/save
        String url = hostAddress + "api.php/gImsi/save";


        for (Imsi imsi : imsis) {
            Map<String, Object> bodyData = new HashMap<>();
            String missionName = MMKVUtils.getString("missionName", "");
            bodyData.put("userid", MMKVUtils.get("username", null));
            bodyData.put("date", date);
            bodyData.put("time", time);
            bodyData.put("site", missionName);
            bodyData.put("deviceid", 0);
            bodyData.put("lat", imsi.getLat());
            bodyData.put("lon", imsi.getLng());
            bodyData.put("high", 0);


            bodyData.put("imsi", imsi);
            bodyData.put("lock", false);
            bodyData.put("strength", imsi.getPower());
            bodyData.put("center", 0);
            bodyData.put("count", count);
            bodyData.put("missionid", missionName);
            bodyData.put("title", missionName);

            bodyDataCache.add(bodyData);
        }
        String body = "";

        try {
            if (true) {

                body = new Gson().toJson(bodyDataCache);
                Request request = new Request.Builder()
                        .url(hostAddress + "api.php/gImsi/save")
                        .post(RequestBody.create(JSON, body))
                        .build();

                okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("uploadImsiDatas", e.getLocalizedMessage());

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        for(Imsi imsi:imsis) {
                            for(int i=0;i<UDPClient.imsilist.size();i++){
                                if(UDPClient.imsilist.get(i).getIsRead()==1){
                                    continue;
                                }

                                if(UDPClient.imsilist.get(i).getImsi().equals(imsi.getImsi())
                                        && UDPClient.imsilist.get(i).getTime() == (imsi.getTime())) {
                                    UDPClient.imsilist.get(i).setIsRead(1);
                                }
                            }
                        }
                    }
                });
                bodyDataCache.clear();
                bodyDataCache = null;
            }

        } catch (Exception e) {
            Log.e("uploadImsiData toJson", e.getLocalizedMessage());
            return;
        }

        // 上传数据结束


    }


    @Override
    public void onResume() {
        super.onResume();
        if (udpClients == null) {
            udpClients = new UDPClient[5];
            UDPClient client90 = new UDPClient("设备90", 0, "192.168.1.90", mHandler, 9001);
            UDPClient client91 = new UDPClient("设备91", 1, "192.168.1.91", mHandler, 9001);
            UDPClient client92 = new UDPClient("设备92", 2, "192.168.1.92", mHandler, 9001);
            UDPClient client93 = new UDPClient("设备93", 3, "192.168.1.93", mHandler, 9001);
            UDPClient client94 = new UDPClient("设备94", 4, "192.168.1.94", mHandler, 9001);
            client90.startUdpConnect();
            client91.startUdpConnect();
            client92.startUdpConnect();
            client93.startUdpConnect();
            client94.startUdpConnect();
            udpClients[0] = client90;
            udpClients[1] = client91;
            udpClients[2] = client92;
            udpClients[3] = client93;
            udpClients[4] = client94;
        }
    }

    public static final int RECEIVE_MSG_FLAG = 0x10;
    public static final int SERVER_STATUS_CHANGE = 0x11;


    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//                super.handleMessage(msg);
            switch (msg.what) {
                case RECEIVE_MSG_FLAG:
//                    udpClients[msg.arg1].getImsilist();
                    loadData();
                    break;
                case SERVER_STATUS_CHANGE:
//                    Log.e(TAG, "handleMessage: " +msg.arg1 +"," + udpClients[msg.arg1].getScanText() );
                    String msgStr = (String) msg.obj;
                    try {
                        if (msgStr.contains("0")) {

                            binding.scanmsg90.setText(msgStr );
                        } else if (msgStr.contains("1")) {
                            binding.scanmsg91.setText(msgStr );
                        } else if (msgStr.contains("2")) {
                            binding.scanmsg92.setText(msgStr );
                        } else if (msgStr.contains("3")) {
                            binding.scanmsg93.setText(msgStr );
                        } else if (msgStr.contains("4")) {
                            binding.scanmsg94.setText(msgStr );
                        }
                    }catch (Exception e){
                        XToastUtils.error("未知错误");
                        e.printStackTrace();
                    }



                    break;
                default:
                    break;
            }

        }
    };


//
//    void startTimerTask(){
//        if(timer!=null) {
//            timer.cancel();
//            timer = null;
//        }
//
//        if(timerTask!=null) {
//            timerTask.cancel();
//            timerTask = null;
//        }
//
//        timer = new Timer();
//        timerTask = new TimerTask() {
//            @Override
//            public void run() {
////                Log.d(TAG, "run: " +  socket.getSize());
////                if(socket.imsi_status==1) {
////                    socket.imsi_status = 0;
////                    loadData();
////                }
//
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(socket!=null)
//                            binding.scanmsg_90.setText(UDPSocket.scanText  );
//
//                    }
//                });
//                count++;
//                if(count>5)count = 0;
//            }
//        };
//        timer.schedule(timerTask,100,500);
//    }

    private String diandian() {
        String dian = "";
        for (int i = 0; i < count; i++) {
            dian += ".";
        }
        return dian;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: " + DetectorFragment.class);
        super.onDestroy();
//        timer.cancel();
//        timerTask.cancel();
//        timer = null;
//        timerTask = null;
        if (udpClients != null) {
            sendMessage("StopCell");
            for (UDPClient udpClient : udpClients) {
                udpClient.stopUdpConnect();
                udpClient = null;
            }
            udpClients = null;
//            socket = null;

        }

    }

    private String workTypeStr = null;
    private String netModeStr = null;
    List<CustomGroupedItem> freqItems = null;
    Map<String, String> loopFreqMap = new HashMap<>();
    Map<String,String> settingMap = null;



    String getFreqItems() {
        List<CustomGroupedItem> freqItems = MMKVUtils.getObjectList(FreqSelectorFragment.FKEY, CustomGroupedItem.class);
        StringBuilder tdd = new StringBuilder();
        StringBuilder fdd = new StringBuilder();
        StringBuilder wcdma = new StringBuilder();
        StringBuilder gsm = new StringBuilder();
        int gsmcount = 0;
        Log.e(TAG, "getFreqItems: " + workTypeStr );
        for (int i = 0; i < freqItems.size(); i++) {
            if (freqItems.get(i).info != null
                    && freqItems.get(i).info.getSelected() == 1) {

                if(null==workTypeStr
                        || workTypeStr.equals("1")) {
                    if (freqItems.get(i).info.getGroup().equals("TDD-移动")) {

                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            tdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }

                    } else if (freqItems.get(i).info.getGroup().equals("FDD-移动") ) {
                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("FDD-联通")) {
                        for (String plmn : IMSIUtil.plmns.get("联通")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("FDD-电信")) {
                        for (String plmn : IMSIUtil.plmns.get("电信")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("WCDMA")) {
                        for (String plmn : IMSIUtil.plmns.get("联通")) {
                            wcdma.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("GSM")) {
                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            //                        SetRfPara 460 0 41134 326 12444 9805 5 41134 0
                            //                        lFor GSM(MCC MNC FCN BSIC LAC cellID txPwr, NBCell，FCN2)
                            //                        SetRfPara 460 11 100 232 329232 23291234 5
                            Log.e(TAG, "getFreqItems: " + freqItems.get(i).info.getContent());

                            if (gsmcount == 0) {
                                gsm = null;
                                gsm = new StringBuilder();
                                gsm.append(" 460 00 " + freqItems.get(i).info.getContent() + " 29 9805 11528 3 ");
                            } else if (gsmcount < 2) {
                                gsm.append(freqItems.get(i).info.getContent());
                            }
                            gsmcount++;

                        }

                    }
                }else{
                    if (freqItems.get(i).info.getGroup().equals("TDD-移动")) {

                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            tdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }

                    } else if (freqItems.get(i).info.getGroup().equals("FDD-移动")) {
                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("FDD-联通")) {
                        for (String plmn : IMSIUtil.plmns.get("联通")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("FDD-电信")) {
                        for (String plmn : IMSIUtil.plmns.get("电信")) {
                            fdd.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("WCDMA")) {
                        for (String plmn : IMSIUtil.plmns.get("联通")) {
                            wcdma.append(" " + freqItems.get(i).info.getContent() + " " + plmn);
                        }
                    } else if (freqItems.get(i).info.getGroup().equals("GSM")) {
                        for (String plmn : IMSIUtil.plmns.get("移动")) {
                            //                        SetRfPara 460 0 41134 326 12444 9805 5 41134 0
                            //                        lFor GSM(MCC MNC FCN BSIC LAC cellID txPwr, NBCell，FCN2)
                            //                        SetRfPara 460 11 100 232 329232 23291234 5
                            Log.e(TAG, "getFreqItems: " + freqItems.get(i).info.getContent());

                            if (gsmcount == 0) {
                                gsm = null;
                                gsm = new StringBuilder();
                                gsm.append(" 460 00 " + freqItems.get(i).info.getContent() + " 29 9805 11527 2 ");
                            } else if (gsmcount < 2) {
                                gsm.append(freqItems.get(i).info.getContent());
                            }
                            gsmcount++;

                        }

                    }
                }
            }
        }

        Log.e(TAG, "getFreqItems:  " + gsm.toString());
        for(String k:settingMap.keySet()){
            Log.e(TAG, "getFreqItems: " + k  + settingMap.get(k));
            if(settingMap.get(k).equals("TDD-LTE")){
                loopFreqMap.put(k, tdd.toString());

            }else if(settingMap.get(k).equals("FDD-LTE")){
                loopFreqMap.put(k, fdd.toString());

            }else if(settingMap.get(k).equals("WCDMA")){
                loopFreqMap.put(k, wcdma.toString());

            }else if(settingMap.get(k).equals("GSM")){
                loopFreqMap.put(k, gsm.toString());

            }else if(settingMap.get(k).equals("GSM-WB")){
                loopFreqMap.put(k, gsm.toString());

            }


        }

//        loopFreqMap.put("192.168.1.92", s90.toString());

        return null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.scanBtn:
//                Log.d("TAG", "onClick: scanBtn"  );
                binding.scanBtn.setClickable(false);
                sendMessage("StopCell");
//                sendMessage("SetCellParaDefault","192.168.1.90");
//                sendMessage("GetBaseWorkCfg ");

//                socket.sendMessage("StopCell","192.168.1.90");

//                                    sendMessage("SetFcnPlmnLoop 10 38950 46000 40936 46002","192.168.1.91");
//                                    sendMessage("SetFcnPlmnLoop 30 1300 46000 1506 46001 1650 46001 1850 46011","192.168.1.91");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            getFreqItems();
//                            sendMessage("GetCellPara ");

                            if(choose_ip==null) {
                                for (String key : loopFreqMap.keySet()) {
                                    Log.e(TAG, "run1: " + key + "  " + loopFreqMap.get(key) + "," + settingMap.get(key));

                                    if (!StringUtils.isEmpty(loopFreqMap.get(key))
                                            && !StringUtils.isEmpty(settingMap.get(key))) {
                                        Log.e(TAG, "run2: " + key + "  " + loopFreqMap.get(key) + "," + settingMap.get(key));


                                        if(settingMap.get(key).equals("GSM")) {
                                            sendMessage("SetRfPara " + loopFreqMap.get(key), key);
                                        }else{
                                            sendMessage("SetFcnPlmnLoop 10" + loopFreqMap.get(key), key);
                                        }

                                    }
                                }
                            }else{
                                Log.e(TAG, "run1: " + choose_ip + "  " + loopFreqMap.get(choose_ip) + "," + settingMap.get(choose_ip));

                                if(settingMap.get(choose_ip).equals("GSM")) {
                                    sendMessage("SetRfPara " + loopFreqMap.get(choose_ip), choose_ip);
                                }else{
                                    sendMessage("SetFcnPlmnLoop 10" + loopFreqMap.get(choose_ip), choose_ip);
                                }
                            }


//                            sendMessage("SetFcnPlmnLoop 5" + loopFreqMap.get("FDD"), "192.168.1.90");


//                            sendMessage("SetFcnPlmnLoop");
//                            sendMessage("SetRfPara 460 0 41134 326 12444 9805 5 41134 0","192.168.1.91");
//                            socket.sendMessage("SetRfPara 460 0 41332 326 12444 9805 5 41134 0","192.168.1.90");
//                            sendMessage("StartSniffer");
//                            socket.sendMessage("StartSniffer","192.168.1.90");

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    try {
//                                        sendMessage("GetCellPara ");
                                        sendMessage("StartCell");
//                                    socket.sendMessage("StartCell","192.168.1.90");
                                        sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0, 10));
//                                    socket.sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0, 10),"192.168.1.90");

                                        binding.scanBtn.setClickable(true);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, 10000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, 10000);
                break;

            case R.id.syncTimeBtn:
                Log.d("TAG", "onClick: syncTimeBtn");
//                socket.sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0,10),"192.168.1.91");``
                sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0, 10), null);
                break;
            case R.id.rebootBtn:
                Log.d("TAG", "onClick: syncTimeBtn");
//                UDPSocket.scanText = "重启";
                sendMessage("stopCell");
                sendMessage("Reboot", null);
//                socket.sendMessage("Reboot","192.168.1.91");
//                socket.sendMessage("Reboot","192.168.1.90");
                break;
            case R.id.uploadDataBtn:

//                wifiManager.setWifiEnabled(false);

                break;
            case R.id.xxooBtn:
//                socket.sendMessage("SetFcnPlmnUpdate 38098 460 00","192.168.1.91");
                sendMessage("");
//                socket.sendMessage("GetRfPara","192.168.1.91");
//                for(UDPClient udpClient:udpClients){
//                    udpClient.sendMessage("GetRfPara");
//                }
//                socket.sendMessage("GetRfPara","192.168.1.90");
                openNewPage(FreqSelectorFragment.class);
//                FragmentManager manager = getActivity().getSupportFragmentManager();
//                FreqDialogFragment dialogFragment = new FreqDialogFragment();
//                dialogFragment.show(manager,"FreqDialogFragment");
//                FreqSelectorFragment dialogFragment = new FreqSelectorFragment();
//                dialogFragment.initViews();


                break;
            case R.id.workTypeBtn:
                Log.d("TAG", "onClick: workTypeBtn");
//                socket.sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0,10));

                XUISimpleAdapter adapter = XUISimpleAdapter.create(getContext(), workTypelistItems);
                mListPopup = new XUIListPopup(getContext(), adapter);
                mListPopup.create(DensityUtils.dp2px(250), DensityUtils.dp2px(200), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        XToastUtils.toast(workTypelistItems[i]);
                        workTypeStr = workTypelistItems[i].substring(0, 1);

                        if(choose_ip==null){
                            workTypeMap = new HashMap<>();
                            workTypeMap.put("192.168.1.90",workTypeStr);
                            workTypeMap.put("192.168.1.91",workTypeStr);
                            workTypeMap.put("192.168.1.92",workTypeStr);
                            workTypeMap.put("192.168.1.93",workTypeStr);
                            workTypeMap.put("192.168.1.94",workTypeStr);


                        }else{
                            if(workTypeMap==null){
                                workTypeMap = new HashMap<>();
                            }
                            workTypeMap.put(choose_ip,workTypeStr);
                        }


                        if (null != blackList) {

//                            socket.sendMessage("SetBlackList " + blackList,"192.168.1.91");
                            sendMessage("SetBlackList " + blackList, null);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    if (null != whiteList) {
//                                        socket.sendMessage("SetWhiteList " + whiteList,"192.168.1.91");
                                        sendMessage("SetWhiteList " + whiteList, null);
                                        setWorkType();

                                    }
                                }
                            }, 5000);
                        } else {

                            if (null != whiteList) {
//                                socket.sendMessage("SetWhiteList " + whiteList,"192.168.1.91");
                                sendMessage("SetWhiteList " + whiteList, null);
                                setWorkType();
                            }

                        }
//                        sendMessage("GetAppCfgExt");
                        mListPopup.dismiss();
                    }
                });
                mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
//                        binding.workTypeBtn.setText("" + );\
                    }
                });

                mListPopup.setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER);
                mListPopup.getListView().setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);
                ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.color.x_recycler_color_text_gray));
                mListPopup.setDivider(sage);
                mListPopup.setDividerHeight(1);
                mListPopup.setPreferredDirection(XUIPopup.DIRECTION_BOTTOM);
                mListPopup.show(v);
                break;
            case R.id.netModeBtn:
                Log.d("TAG", "onClick: netModeBtn");
//                socket.sendMessage("SetTime " + String.valueOf(System.currentTimeMillis()).substring(0,10));

                XUISimpleAdapter netModeAdapter = XUISimpleAdapter.create(getContext(), netModelistItems);
                mListPopup = new XUIListPopup(getContext(), netModeAdapter);
                mListPopup.create(DensityUtils.dp2px(150), DensityUtils.dp2px(200), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        XToastUtils.toast(netModelistItems[i]);
                        netModeStr = netModelistItems[i];
                        Log.e(TAG, "choose_ip: " + choose_ip );
                        if(!StringUtils.isEmpty(choose_ip)){

                            settingMap.put(choose_ip,netModeStr );
//                            Log.e(TAG, "onItemClick: " + new Gson().toJson(settingMap) );

                            MMKVUtils.put("setting",new Gson().toJson(settingMap));

                            sendMessage("SwitchNetMode " + netModeStr );

                            if (netModeStr.contains("TDD")) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        sendMessage("SetSynMode 2 ");
                                    }
                                }, 8000);
                            }

                        }else{
                            XToastUtils.error("未选择设备");
                        }

//                        sendMessage("SetCellParaDefault");


                        mListPopup.dismiss();
                    }
                });
                mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
//                        binding.workTypeBtn.setText("" + );


                    }
                });
                mListPopup.setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER);
                sage = new ColorDrawable(this.getResources().getColor(R.color.x_recycler_color_text_gray));
                mListPopup.setDivider(sage);
                mListPopup.setDividerHeight(1);
                mListPopup.setPreferredDirection(XUIPopup.DIRECTION_BOTTOM);
                mListPopup.show(v);
                break;
            default:
                break;
        }

    }

    /**
     * @param cmd 命令
     * @author samdodo
     * 发送消息
     */
    private void sendMessage(String cmd) {
        Log.e(TAG, "sendMessage: " + cmd);

        if (StringUtils.isEmpty(choose_ip)) {
            for (UDPClient udpClient : udpClients) {
                udpClient.sendMessage(cmd + " " + String.valueOf(System.currentTimeMillis()).substring(0, 10));
            }
        } else {
            for (UDPClient udpClient : udpClients) {
                if (choose_ip.equals(udpClient.getServer_ip()))
                    udpClient.sendMessage(cmd + " " + String.valueOf(System.currentTimeMillis()).substring(0, 10));
            }
        }
    }

    /**
     * @param cmd 命令
     * @param ip  IP地址
     * @author samdodo
     * 发送消息
     */
    private void sendMessage(String cmd, String ip) {
        Log.e(TAG, "sendMessage: " + cmd + " , " + ip);
        if (!StringUtils.isEmpty(ip)) {
            for (UDPClient udpClient : udpClients) {
                if (udpClient.getServer_ip().equals(ip))
//                    udpClient.sendMessage(cmd + " " + String.valueOf(System.currentTimeMillis()).substring(0,10));
                    udpClient.sendMessage(cmd);
            }
        } else {

            sendMessage(cmd);
        }

    }

    private void setWorkType() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                socket.sendMessage("SetWorkType " + workTypeStr,"192.168.1.91");
                sendMessage("SetWorkType " + workTypeStr);
            }
        }, 3000);
    }


    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        // 添加左侧的，如果不添加，则左侧不会出现菜单。
        {
            SwipeMenuItem addItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_green)
                    .setText("跟踪")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeLeftMenu.addMenuItem(addItem); // 添加菜单到左侧。

            SwipeMenuItem closeItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_red)
//                    .setImage(R.drawable.ic_swipe_menu_close)
                    .setText("取消")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeLeftMenu.addMenuItem(closeItem); // 添加菜单到左侧。
        }

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        {
            SwipeMenuItem deleteItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_red)
//                    .setImage(R.drawable.ic_swipe_menu_delete)
                    .setText("黑名单")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

            SwipeMenuItem addItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_green)
                    .setText("白名单")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {

//            XToastUtils.toast("list第" + position + "; 右侧菜单第" + menuPosition);
            XToastUtils.toast("" + UDPClient.imsilist.get(position).getImsi() + "; 右侧菜单第" + menuPosition);
            int isWhite = 1;
            if(menuPosition==0){
                //黑名单
                isWhite = 0;
            }

            ListItem item = ItemDao.findAllByListIdAndImsi(missionId,UDPClient.imsilist.get(position).getImsi());
            if(null != item){
                item.setIsWhite(isWhite);
                ItemDao.update(item);
            }else{
                ItemDao.add(new ListItem(missionId, isWhite, UDPClient.imsilist.get(position).getImsi()));
            }




        } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
            XToastUtils.toast("list第" + position + "; 左侧菜单第" + menuPosition);
        }
    };

    @Override
    protected void initListeners() {
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(this::loadData);
        refresh(); //第一次进入触发自动刷新，演示效果
    }

    private void refresh() {
        binding.refreshLayout.setRefreshing(true);
        loadData();
    }

    public static LinkedList<String> imsistrlist = null;

    public void loadData() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.refresh(UDPClient.imsistrlist);
                if (binding.refreshLayout != null) {
                    binding.refreshLayout.setRefreshing(false);
                }

            }
        });

    }


    private static final String GPS_LOCATION_NAME = android.location.LocationManager.GPS_PROVIDER;
    private static final int REQUEST_PRESSMION_CODE = 10000;
    private final static String[] MULTI_PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

    private LocationManager locationManager;
    private boolean isGpsEnabled;
    private String locateType;


    /**
     * 方法描述：初始化定位相关数据
     */
    private void initData() {
        //获取定位服务
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        //判断是否开启GPS定位功能
        isGpsEnabled = locationManager.isProviderEnabled(GPS_LOCATION_NAME);
        //定位类型：GPS
        locateType = locationManager.GPS_PROVIDER;
        //初始化PermissionHelper

        getLocation();

    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this.getActivity(), MULTI_PERMISSIONS, REQUEST_PRESSMION_CODE);
            return;
        }
        Location location = locationManager.getLastKnownLocation(locateType); // 通过GPS获取位置
        if (location != null) {
//            updateUI(location);
        }
        // 设置监听*器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        locationManager.requestLocationUpdates(locateType, 1000, 0,
                locationListener);
    }

    private LocationListener locationListener = new LocationListener() {
        /**
         * 位置信息变化时触发:当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
//            XToastUtils.toast("onLocationChanged函数被触发");
//            updateUI(location)  ;
//            Log.i(TAG, "时间：" + location.getTime());
//            Log.i(TAG, "经度：" + location.getLongitude());
            lng = location.getLongitude();
            lat = location.getLatitude();
//            Log.i(TAG, "纬度：" + location.getLatitude());
//            Log.i(TAG, "海拔：" + location.getAltitude());
        }

        /**
         * GPS状态变化时触发:Provider被disable时触发此函数，比如GPS被关闭
         * @param provider
         * @param status
         * @param extras
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
                    XToastUtils.toast("onStatusChanged：当前GPS状态为可见状态");
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
                    XToastUtils.toast("onStatusChanged：当前GPS状态为服务区外状态");
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    XToastUtils.toast("onStatusChanged：当前GPS状态为暂停服务状态");
                    break;
            }
        }

        /**
         * 方法描述：GPS开启时触发
         * @param provider
         */
        @Override
        public void onProviderEnabled(String provider) {
//            Toast.makeText(MainActivity.this, "onProviderEnabled:方法被触发", Toast.LENGTH_SHORT).show();
            XToastUtils.toast("onProviderEnabled:方法被触发");
            Log.e(TAG, "onProviderEnabled: 方法被触发");
            getLocation();
        }

        /**
         * 方法描述： GPS禁用时触发
         * @param provider
         */
        @Override
        public void onProviderDisabled(String provider) {

        }
    };


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                lat = amapLocation.getLatitude();//获取纬度
                lng = amapLocation.getLongitude();//获取经度
                Log.e(TAG, "onLocationChanged: " + lat + "," + lng);
                amapLocation.getAccuracy();//获取精度信息
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(amapLocation.getTime());
//                df.format(date);//定位时间
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }
}

